package com.iron.visual.codegen.service.impl;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iron.visual.codegen.entity.GenConfig;
import com.iron.visual.codegen.mapper.OracleGeneratorMapper;
import com.iron.visual.codegen.service.SysGeneratorService;
import com.iron.visual.codegen.uitl.GenUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * oracle 代码生成器
 *
 * @author YT
 * @date 2019-06-18
 */
@Service("oracleGeneratorService")
@AllArgsConstructor
public class OracleGeneratorServiceImpl implements SysGeneratorService {

    private final OracleGeneratorMapper oracleGeneratorMapper;

    @Override
    public IPage<List<Map<String, Object>>> getPage(Page page, String tableName) {
        List<Map<String, Object>> list = oracleGeneratorMapper.queryList(tableName);
        page.setRecords(list);
        return page;
    }

    /**
     * 生成代码
     *
     * @param genConfig 生成配置
     * @return
     */
    @Override
    public byte[] generatorCode(GenConfig genConfig) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        // 查询表信息
        Map<String, String> table = queryTable(genConfig.getTableName());
        // 查询列信息
        List<Map<String, String>> colums = queryColumns(genConfig.getTableName());
        // 生成代码
        GenUtils.generatorCode(genConfig, table, colums, zip);
        IoUtil.close(zip);
        return outputStream.toByteArray();
    }

    @Override
    public Map<String, String> queryTable(String tableName) {
        return oracleGeneratorMapper.queryTable(tableName);
    }

    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        return oracleGeneratorMapper.queryColumns(tableName);
    }

}
